const querystring = require("querystring");
const { get } = require("./src/db/redis");
const handleBlogRouter = require("./src/router/blog");
const handleUserRouter = require("./src/router/user");
const { access } = require("./src/utils/log");

const getCookieExpires = () => {
  return new Date()
    .setTime(new Date().getTime() + 60 * 60 * 1000)
    .toGMTString();
};
// const session_data = {};

const getPostData = (req) => {
  return new Promise((resolve, reject) => {
    if (req.method !== "POST") {
      return resolve({});
    }
    if (req.headers["content-type"] !== "application/json") {
      return resolve({});
    }
    let postData = "";
    req.on("data", (chunk) => {
      postData += chunk.toString();
    });
    req.on("end", () => {
      if (!postData) return resolve({});
      resolve(JSON.parse(postData));
    });
  });
};

const serverHandle = (req, res) => {
  res.setHeader("Content-type", "application/json");

  const url = req.url;
  req.path = url.split("?")[0];
  req.query = querystring.parse(url.split("?")[1]);
  console.log(req.path, req.query, "path ... query");
  req.cookie = {};
  const cookies = req.headers.cookie || "";
  let { method, path, headers } = req;

  access(
    `${method} -- ${path}
    ${headers["user-agent"]} 
    ${new Date().toGMTString()}`
  );

  cookies.split(";").forEach((i) => {
    if (i) {
      let [key, value] = i.split("=");
      req.cookie[key] = value;
    }
  });
  console.log(req.cookie, "req..cookie..");
  let sessionId = req.cookie.sessionId;
  console.log("=== === === ", sessionId);
  req.session = {};
  if (sessionId) {
    req.sessionId = sessionId;
    get(sessionId).then((sdata) => {
      req.session = sdata;
      getPostData(req).then((postData) => {
        req.body = postData;

        const blogData = handleBlogRouter(req, res);
        if (blogData) {
          return blogData.then((data) => {
            res.end(JSON.stringify(data));
          });
        }
        // if (blogData) return res.end(JSON.stringify(blogData));

        const userData = handleUserRouter(req, res);

        if (userData) {
          return userData.then((userData) => {
            res.end(JSON.stringify(userData));
          });
        }

        //404
        res.end("404 not found");
      });
      console.log(res, "session id info");
    });
  } else {
    req.sessionId = Date.now();
    console.log(req.sessionId, "iddid");
    req.needSetCookie = true;
    getPostData(req).then((postData) => {
      req.body = postData;

      const blogData = handleBlogRouter(req, res);
      if (blogData) {
        return blogData.then((data) => {
          res.end(JSON.stringify(data));
        });
      }
      // if (blogData) return res.end(JSON.stringify(blogData));

      const userData = handleUserRouter(req, res);

      if (userData) {
        return userData.then((userData) => {
          res.end(JSON.stringify(userData));
        });
      }

      //404
      res.end("404 not found");
    });
    // session_data[userid] = {};
  }
  // req.session = session_data[userid];
  // console.log("session_date...", session_data);
};
module.exports = serverHandle;
